package tech.dongliang.common.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.exception.BizException;
import tech.dongliang.common.response.CommonResponse;
import tech.dongliang.common.response.ErrorData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 统一异常处理
     * 所有层异常抛到controller统一处理
     * 异常以json返回给用户，http状态码为200，
     * @param req
     * @param rsp
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResponse handleError(HttpServletRequest req, HttpServletResponse rsp, Exception ex) {
        if (ex instanceof BizException) {
            BizException e = (BizException) ex;
            return CommonResponse.create(new ErrorData(e), false);
        } else {
            log.error(ex.getMessage(), ex);
            return CommonResponse.create(new ErrorData(EBizError.UNKNOWE_ERROR), false);
        }
    }
}
